from django.shortcuts import render, HttpResponse
from django.http.response import JsonResponse,HttpResponseRedirect
from django.views.generic import View, TemplateView
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse

# Create your views here.
class BaseView(View):
    def get(self, request):
        return render(request, 'base.html')


class IndexView(LoginRequiredMixin, View):
    def get(self, request):
        user_count = 200
        return render(request, 'index.html', locals())


# class IndexView(TemplateView):
#     template_name = 'index.html'
#
#     # 重写方法 实现数据传输
#     def get_context_data(self, **kwargs):
#         context = super().get_context_data()
#         context['user_count'] = 100
#         return context
# 加载登录页面的视图方法 不要校验是否具有权限(登录权限)
class LoginView(TemplateView):
    template_name = 'login.html'

    def post(self, request):
        # print(request.POST)
        username = request.POST.get('username')
        password = request.POST.get('password')
        # authenticate 查数据表  auth_user
        user = authenticate(username=username, password=password)
        if user:
            # 登录操作 写session
            login(request, user)
            res = {'status': 0, 'msg': '登录成功'}
        else:
            res = {'status': 1, 'msg': '用户名或者密码错误'}
        # return HttpResponse('登录数据测试')
        return JsonResponse(res)

class LogoutView(View):
    def get(self,request):
        logout(request)
        return HttpResponseRedirect(reverse('user_login'))